<template>
  <el-dialog :title="state=='check'?'查看内容':!dataForm.id ? '发送消息' : '复制发送'" :close-on-click-modal="false" :visible.sync="visible">
    <el-form v-if="state!='check'" :model="dataForm" :rules="dataRule" ref="dataForm" label-width="80px">

      <!-- 第一页 -->
      <div v-if="step == 1">
        <el-form-item label="模板" prop="templateId">
          <el-select v-model="dataForm.templateId" filterable clearable placeholder="请选择" @change="choiceTemplate">
            <el-option v-for="item in templateList" :key="item.templateId" :label="item.title" :value="item.templateId">
            </el-option>
          </el-select>
        </el-form-item>
      </div>

      <!-- 第二页 -->
      <div v-if="step == 2">
          <el-form-item v-if="template.title!=undefined" label="跳转链接" >
                    <el-input v-model="template.url" placeholder="跳转链接">
                        <div slot="append" @click="publishFlag=true">从素材库中选择</div>
                    </el-input>
                </el-form-item>
        <span>{{template.title!=undefined?template.title+':':'未选择模板！'}}</span>
        <div class="form-group-area" style="margin-top: 10px;">
          <el-row v-for="(item, index) in template.data" :key="item.label">
            <el-col :span="16">
              <el-form-item :label="item.label" :prop="'data.' + index + '.value'"
                :rules="[{ required: true, message: '填充内容不得为空', trigger: 'blur' }]">
                <el-input type="textarea" autosize rows="1" v-model="item.value" placeholder="填充内容"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="颜色">
                <el-input type="color" v-model="item.color" placeholder="颜色"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </div>


      <!-- 第三页 -->
      <div v-if="step == 3">
        <el-form :inline="true" :model="userDataForm" ref="userDataForm" clearable @keyup.enter.native="getWxUsers()">
          <el-form-item>
            <el-select v-model="userDataForm.tagid" filterable placeholder="用户标签" clearable @change="getWxUsers()">
              <el-option v-for="item in wxUserTags" :key="item.id" :label="item.name" :value="item.id + ''"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <!-- <el-input v-model="userDataForm.communityId" placeholder="小区" @change="getWxUsers()" clearable></el-input> -->
            <el-select v-model="userDataForm.communityId" filterable placeholder="小区" clearable @change="changeAddress">
              <el-option v-for="item in communityList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <!-- <el-input v-model="userDataForm.buildingNoId" placeholder="楼号" @change="getWxUsers()" clearable></el-input> -->
            <el-select v-if="userDataForm.communityId != '' && userDataForm.communityId != undefined"
              v-model="userDataForm.buildingNoId" filterable placeholder="楼号" clearable @change="changeAddress">
              <el-option v-for="item in buildingNoList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <!-- <el-input v-model="userDataForm.unitId" placeholder="单元" @change="getWxUsers()" clearable></el-input> -->
            <el-select v-if="userDataForm.buildingNoId != '' && userDataForm.buildingNoId != undefined"
              v-model="userDataForm.unitId" filterable placeholder="单元" clearable @change="getWxUsers()">
              <el-option v-for="item in unitIdList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div class="text-bold">本消息将发送给
          <!--           ：
        </div>
        <div class="user-list"  v-loading="wxUsersLoading">
            <div class="user-card" v-for="item in wxUserList" :key="item.openid">
                <el-avatar :src="item.headimgurl"></el-avatar>
                <div class="nickname">{{item.nickname}}</div>
            </div>
            <div class="text-bold">
                <span v-show="totalCount>10">...</span> 
                等-->
          共<span class="text-success">{{ totalCount }}</span>个用户

        </div>
        <div class="margin-top text-bold">消息预览：</div>
        <div class="margin-top-xs">
          <el-input type="textarea" disabled autosize v-model="msgReview" placeholder="模版"></el-input>
        </div>
      </div>
    </el-form>
    <div v-else class="margin-top-xs">
          <el-input type="textarea" disabled autosize v-model="msgReview" placeholder="模版"></el-input>
        </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button v-if="step != 1&&state!='check'" type="primary" @click="step -= 1">上一步</el-button>
      <el-button v-if="step != 3&&state!='check'" type="primary" @click="next()">下一步</el-button>
      <el-button v-if="step == 3&&state!='check'" type="primary" :loading="loading" @click="dataFormSubmit()">发送</el-button>
    </span>
    <publish-selector v-if="publishFlag" :visible="publishFlag" selectType="image" @onClose = "onClose" @selected="onPublishSelect"></publish-selector>
  </el-dialog>
</template>

<script>
import { mapState } from 'vuex'
import { treeDataTranslate, treeDataSelect } from '@/utils'
import storage from 'store'
export default {
  components: {
        PublishSelector:()=>import('./publish-selector')
    },
  data() {
    return {
      state: '',
      step: 1,
      visible: false,
      wxUsersLoading: false,
      publishFlag:false,
      loading:false,
      dataForm: {
        id: 0,
        appid: '',
        tagid: '',
        tagName: '',
        addressId: '',
        addressName: '',
        templateId: '',
        templateName: '',
        data: '',
        sendData: '',
        dataName: '',
        url: '',
        miniprogram: '',
        sendDate: '',
        sender: ''
      },
      userDataForm: {
        tagid: '',
        address: []
      },
      template: {},
      templateList: [],
      wxUserList: [],
      communityList: [],
      buildingNoList: [],
      unitIdList: [],
      totalCount: 0,
      dataRule: {
        templateId: [
          { required: true, message: '公众号模板ID不能为空', trigger: 'blur' }
        ],
      }
    }
  },
  computed: mapState({
    wxUserTags: state => state.wxUserTags.tags,
    msgReview() {
      if (!this.template.data) return ""
      let content = this.template.content
      this.template.data.forEach(item => {
        content = content.replace("{{" + item.name + ".DATA}}", item.value)
      })
      this.template.title
      content = this.template.title + '\n' + content
      return content
    }
  }),
  mounted() {
    this.getWxUserTags().then((taglist) => {
      if (this.wxUserTagName) {
        let tagItem = taglist.find(tag => tag.name == this.wxUserTagName)
        if (tagItem) {
          this.dataForm.tagid = tagItem.id + ''
        }
      }
      this.getWxUsers()
    });
  },
  methods: {
    init(id) {
      this.state = ''
      this.clear()
      this.$http({
        url: this.$http.adornUrl('/manage/msgTemplate/all'),
        method: 'get',
        params: this.$http.adornParams({
        })
      }).then(({ data }) => {
        if (data && data.code === 200) {
          this.templateList = data.page
          this.$http({
            url: this.$http.adornUrl('/sys/address/list'),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({ data }) => {
            if (data && data.code === 200) {
              this.communityList = treeDataTranslate(data.page)
              this.getWxUsers()
              this.info(id)
            }
          })
        }
      })
    },
    check(id){
      this.state = 'check'
      this.clear()
      this.$http({
        url: this.$http.adornUrl('/manage/msgTemplate/all'),
        method: 'get',
        params: this.$http.adornParams({
        })
      }).then(({ data }) => {
        if (data && data.code === 200) {
          this.templateList = data.page
          this.$http({
            url: this.$http.adornUrl('/sys/address/list'),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({ data }) => {
            if (data && data.code === 200) {
              this.communityList = treeDataTranslate(data.page)
              this.getWxUsers()
              this.info(id)
            }
          })
        }
      })
    },
    info(id) {
      this.dataForm.id = id
      this.visible = true
      if (this.dataForm.id) {
        this.$http({
          url: this.$http.adornUrl(`/wx/wxtemplatelog/info/${this.dataForm.id}`),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({ data }) => {
          if (data && data.code === 200) {
            this.step = 2
            var address = data.wxTemplateLog.addressId.replace("[", "").replace("]", "").split(', ');
            // this.$set(this.userDataForm, 'tagid', data.wxTemplateLog.tagid)
            this.getWxUsers()
            // if (address[0] != '') {
            //   this.$set(this.userDataForm, 'communityId', address[0] * 1)
            //   this.getWxUsers()
            //   this.changeAddress(address[0] * 1)
            //   if (address[1] != '') {
            //     this.$set(this.userDataForm, 'buildingNoId', address[1] * 1)
            //     this.getWxUsers()
            //     this.changeAddress(address[1] * 1)
            //   }
            //   if (address[2] != '') {
            //     this.$set(this.userDataForm, 'unitId', address[2] * 1)
            //     this.getWxUsers()
            //   }
            // }
            this.dataForm.templateId = data.wxTemplateLog.templateId
            this.dataForm.templateName = data.wxTemplateLog.templateName
            this.dataForm.url = data.wxTemplateLog.url
            this.dataForm.miniprogram = data.wxTemplateLog.miniprogram
            this.choiceTemplate(data.wxTemplateLog.templateId)
            
            this.template.data = this.convertData(data.wxTemplateLog.data)
            this.template.url = data.wxTemplateLog.url
          }
        })
      } else {
        this.step = 1
        this.clear()
      }
    },
    convertData(data){
      var newDataList = []
      var dataList = data.replace("[", "").replace("]", "").split('}, ')
            for (let index = 0; index < dataList.length; index++) {
              var newData = {}
              var list = dataList[index].replace("{", "").replace("}", "").split(', ')
              for (let i = 0; i < list.length; i++) {
                this.$set(newData,list[i].split(':')[0],list[i].split(':')[1])
              }
              newDataList.push(newData)
            }
      return newDataList
    },
    clear() {
      this.dataForm = {
        appid: '',
        tagid: '',
        tagName: '',
        addressId: '',
        addressName: '',
        templateId: '',
        templateName: '',
        data: '',
        sendData: '',
        dataName: '',
        url: '',
        miniprogram: '',
        sendDate: '',
        sender: ''
      }

      this.template = {}

      this.userDataForm = {}

    },
    next(){
      if (this.step==1) {
        if(this.dataForm.templateId==''){
        this.step = 1
        this.$message.error("模板不能为空!")
        this.loading = false
      }else{this.step += 1}
      }
      else if(this.step==2){
        var flag = false
        var sizes = 0
        this.template.data.forEach(element => {
          sizes+=element.value.length
          if (element.value=='') {
            flag = true
          }
        });
        if(flag){
        this.step = 2
        this.$message.error("填充内容不得为空!")
        this.loading = false
      }else if (sizes>200) {
        this.step = 2
        this.$message.error("填充内容过多!")
        this.loading = false
        }else{
          this.step += 1
        }
      }else{
        this.step += 1
      }
    },
    // 表单提交
    dataFormSubmit() {
      this.loading = true
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(`/wx/wxtemplatelog/save`),
            method: 'post',
            data: this.$http.adornData({
              'id': this.dataForm.id || undefined,
              'appid': this.dataForm.appid,
              'tagid': this.userDataForm.tagid,
              'tagName': this.getTagName(this.userDataForm.tagid),
              'addressId': this.getAddress().id,
              'addressName': this.getAddress().name,
              'templateId': this.dataForm.templateId,
              'templateName': this.dataForm.templateName,
              'data': this.template.data,
              'sendData': this.sendData(),
              'dataName': this.dataForm.dataName,
              'url': this.template.url,
              'miniprogram': this.template.miniprogram,
              // 'setSender':this.$store.state.user.name
            })
          }).then(({ data }) => {
            if (data && data.code === 200) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.loading = false
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.loading = false
              this.$message.error(data.msg)
            }
          })
        }else{
          this.loading = false
        }
      })
    },
    sendData() {
      if (!this.template.data) return ""
      let content = this.template.content
      this.template.data.forEach(item => {
        content = content.replace("{{" + item.name + ".DATA}}", item.value)
      })
      return content
    },
    getWxUserTags() {
      return new Promise((resolve, reject) => {
        this.$http({
          url: this.$http.adornUrl('/manage/wxUserTags/list'),
          method: 'get',
        }).then(({ data }) => {
          if (data && data.code === 200) {
            this.$store.commit('wxUserTags/updateTags', data.list)
            resolve(data.list)
          } else {
            this.$message.error(data.msg)
            reject(data.msg)
          }
        }).catch(err => reject(err))
      })
    },
    selectTemplate() {
      this.$http({
        url: this.$http.adornUrl('/manage/msgTemplate/all'),
        method: 'get',
        params: this.$http.adornParams({
        })
      }).then(({ data }) => {
        if (data && data.code === 200) {
          this.templateList = data.page
        }
      })
    },
    selectAddress() {
      this.$http({
        url: this.$http.adornUrl('/sys/address/list'),
        method: 'get',
        params: this.$http.adornParams()
      }).then(({ data }) => {
        if (data && data.code === 200) {
          this.communityList = treeDataTranslate(data.page)
          return this.communityList
        }
      })
    },
    changeAddress(data) {
      if (data != "") {
        var address = treeDataSelect(this.communityList, data)
        if (address.type == 0) {
          this.buildingNoList = address.children
          this.$set(this.userDataForm, 'buildingNoId', '')
          this.$set(this.userDataForm, 'unitId', '')
        } else if (address.type == 1) {
          this.unitIdList = address.children
          this.$set(this.userDataForm, 'unitId', '')
        }
      }
      this.getWxUsers()

    },
    onClose(){
      this.publishFlag = false
    },
    onPublishSelect(publish){
      this.template.url = publish.url
      this.publishFlag = false
    },
    getTagName(tagid) {
      if (tagid != '') {
        for (var i = 0; i < this.wxUserTags.length; i++) {
          if (this.wxUserTags[i].id == tagid)
            return this.wxUserTags[i].name
        }
      }
    },
    getAddress() {
      var id = []
      var name = ""
      if (this.userDataForm.communityId != null && this.userDataForm.communityId != '') {
        id.push(this.userDataForm.communityId)
        name = name + treeDataSelect(this.communityList, this.userDataForm.communityId).name
        if (this.userDataForm.buildingNoId != null && this.userDataForm.buildingNoId != '') {
          id.push(this.userDataForm.buildingNoId)
          name = name + treeDataSelect(this.communityList, this.userDataForm.buildingNoId).name
          if (this.userDataForm.unitId != null && this.userDataForm.unitId != '') {
            id.push(this.userDataForm.unitId)
            name = name + treeDataSelect(this.communityList, this.userDataForm.unitId).name
          }
        }
      }
      return {
        id: id,
        name: name
      }
    },
    choiceTemplate(templateId) {
      if (templateId != '') { 
        var index = this.templateList.findIndex(item => {
          if (item.templateId == templateId) {
            return true;
          }
        })
        this.template = this.templateList[index]
        this.dataForm.templateName = this.template.title
      }
    },
    getWxUsers() {
      this.wxUsersLoading = true
      if (this.userDataForm.communityId == '') {
        this.$set(this.userDataForm, 'buildingNoId', '')
        this.$set(this.userDataForm, 'unitId', '')
      } else if (this.userDataForm.buildingNoId == '') {
        this.$set(this.userDataForm, 'unitId', '')
      }
      this.$http({
        url: this.$http.adornUrl('/manage/wxUser/list'),
        method: 'get',
        params: this.$http.adornParams(this.userDataForm)
      }).then(({ data }) => {
        if (data && data.code === 200) {
          this.wxUserList = data.page.list
          this.totalCount = data.page.totalCount
        } else {
          this.$message.error(data.msg)
        }
        this.wxUsersLoading = false
      })


    },

  }
}
</script>
